****************************************************************************************
*This file load and process alternative drought measures and cross walk them to the county-level
****************************************************************************************
// Alternative drought indices from: https://www.ncei.noaa.gov/access/monitoring/climate-at-a-glance/
// https://www.ncei.noaa.gov/pub/data/cirs/climdiv/

clear all
cd "$root"

******************Process data on alternative drought measures*****************
**# This builds the crosswalk between county and climate division
import delimited data\raw\NCEI\county-to-climdivs.txt, delimiter(whitespace, collapse) varnames(3) rowrange(4) clear 
drop  ncdc_fips_id
ren (postal_fips_id climdiv_id) (fips div)
drop if missing(fips)
expand 24
bysort fips: gen year = _n + 1999
save data\temp\div_fips, replace

**# Import climate-division-level 
foreach var in pdsi phdi pmdi{
	import delimited data\raw\NCEI\climdiv-`var'dv-v1.0.0-20240705.txt, delimiter(whitespace, collapse) clear 
	drop v14

	* The first variable is division-index-year, the rest are monthly numbers from Jan to Dec.
	rename v1 div_year
	forvalues m = 2(1)13 {
		local n = `m' - 1
		replace v`m' = . if v`m' < -99 
		rename v`m' `var'_`n'
	}

	gen year = div_year - trunc(div_year/10000)*10000
	gen div = trunc(div_year/1000000)
	drop div_year
	drop if year < 2000  // These drought indices go back to 1895
	order div year

	if ("`var'"=="pdsi") {
			save data\temp\alt_drought_data, replace
		}
		else {
			merge 1:1 div year using data\temp\alt_drought_data,nogen
			save data\temp\alt_drought_data, replace
		}
}

/*
PDSI: Palmer’s drought index
PHDI: Palmer Hydrological Drought index
PMDI: Modified Palmer drought severity index
*/

**# Create dry and wetness variables
foreach var in pdsi phdi pmdi {
	forvalues j = 1(1)12 {
		replace `var'_`j' = -`var'_`j'
		gen `var'_w_`j' = -`var'_`j'
		replace `var'_w_`j' = 0 if `var'_`j'>0
		replace `var'_`j'  = 0 if `var'_`j'<0
	}
}

save data\temp\alt_drought_temp, replace

gen double divyr = div*100000 + year
merge 1:m div year using data\temp\div_fips
keep if _merge == 3
drop _merge
drop div div*
gen double fips_year = fips*10000+year
reshape long pmdi_ phdi_ pdsi_ pmdi_w_ phdi_w_ pdsi_w_, i(fips year) j(month)

ren *_ *

erase data\temp\div_fips.dta
erase data\temp\alt_drought_data.dta
erase data\temp\alt_drought_temp.dta

save "data\temp\alt_drought_long.dta", replace


